class Subject {
constructor () {
this.observerList = [];
}
attach (observer) {
const ob = this.observerList.find(itm => itm === observer);
if (!ob) {
this.observerList.push(observer);
}
return this
}
detach (observer) {
const obIndex = this.observerList.findIndex(itm => itm === observer);
return obIndex > -1
? this.observerList.splice(obIndex, 1)[0]
: this;
}
notify (state) {
if (this.observerList.length) {
this.observerList.forEach(observer => {
observer instanceof Observer && observer.update(state);
})
}
return this;
}
}
class Observer {
constructor () {}
update () {
console.error('子类请重写 update 方法!');
}
}
class ConcreteSubject extends Subject {
constructor () {
super();
this.value = null;
}
set state (value) {
this.value = value;
this.notify(value);
}
get state (value) {
return this.value;
}
}
class ConcreteObserver extends Observer {
constructor (fn) {
super();
this.updateFn = fn;
}
update (state) {
this.updateFn(state);
}
}
const ob1Update = price => {
if (price > 1000) {
console.log('价格高于 1000,fuck!');
} else {
console.log('价格小于 1000,God Bless Me!');
}
}
const ob2Update = price => {
if (price > 2000) {
console.log('价格高于 2000,fuck!');
} else {
console.log('价格小于 2000,God Bless Me!');
}
}
let subject = new ConcreteSubject();
let ob1 = new ConcreteObserver(ob1Update);
let ob2 = new ConcreteObserver(ob2Update);
subject.attach(ob1).attach(ob2);
subject.state = 3000;